﻿using System.Data;

namespace FancyIdea.PingShui.Core.DbHelper
{
    /// <summary>
    /// DataRowWrapper类用于包装一个或多个DataRow对象，以使从DataRow对象获取
    /// 数据更加容易
    /// </summary>
    public class DataRowWrapper
    {
        /// <summary>
        /// 获取或设置DataRow对象
        /// </summary>
        public DataRow DataRow;

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public DataRowWrapper()
        {
        }

        /// <summary>
        /// 构造函数，构造时即封装一个DataRow对象。
        /// 稍后也可以通过DataRow属性更改被封装的DataRow对象
        /// </summary>
        /// <param name="dataRow"></param>
        public DataRowWrapper(DataRow dataRow)
        {
            this.DataRow = dataRow;
        }

        /// <summary>
        /// 获取字符串值
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public string GetStringValue(string field)
        {
            return DataRow[field] as string;
        }

        /// <summary>
        /// 获取任意类型值，并指定默认值。如果从DataRow中指定字段为DbNull时
        /// 则返回默认值。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="field"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public T GetValue<T>(string field, T defaultValue)
        {
            return DataRow.IsNull(field) ? defaultValue : (T)DataRow[field];
        }

        /// <summary>
        /// 获取任意类型值。如果DataRow对象中指定字段为DbNull时返回该字段类型
        /// 的默认值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="field"></param>
        /// <returns></returns>
        public T GetValue<T>(string field)
        {
            return GetValue<T>(field, default(T));
        }
    }
}
